// 摄像头操作工具
const CameraUtil = {
  isOpen: false,
  mediaStreamTrack: null,

  // 摄像头设置项
  options: {
    video: {
      width: 300,
      height: 200,
    },
    // 不开启声音
    audio: false,
  },
  // 开启摄像头
  openCamera: function (id) {
    // 添加摄像头容器
    // $("#" + id + "").empty();
    // $("#" + id + "").append(
    // "<video id='video'></video><canvas id='canvas' width='" +
    // this.options.video.width +
    // "px' height='" +
    // this.options.video.height +
    // "px' style='display: none'></canvas>"
    // );
    // 开启摄像头
    // play 为 DOM 对象方法，所以不能用 JQuery 元素选择器
    navigator.mediaDevices.getUserMedia(this.options).then((mediaStream) => {
      document.getElementById("video").srcObject = mediaStream;
      document.getElementById("video").play();
      this.mediaStreamTrack = mediaStream.getTracks()[0];
    });
    // 设置开启标识
    this.isOpen = true;
  },
  // 关闭摄像头
  closeCamera: function () {
    if (this.mediaStreamTrack != null) {
      this.mediaStreamTrack.stop();
      this.mediaStreamTrack = null;
      this.isOpen = false;
      // $("#video").hide();
      this.cameraShow = false;
    }
  },
  // 拍照、canvas 绘图、返回图片 base64 编码
  getImage: function () {
    if (this.isOpen) {
      var ctx = document.getElementById("canvas").getContext("2d");
      ctx.drawImage(document.getElementById("video"), 0, 0, this.options.video.width, this.options.video.height);
      // Data URI scheme
      // data:image/png;base64, 开头，代表 base64 编码的 png 图片数据
      var imageCode = document.getElementById("canvas").toDataURL().replace("data:image/png;base64,", "");
      return imageCode;
    } else {
      console.log("没有开启摄像头.");
      return "";
    }
  },
};
export default CameraUtil;
